package com.zj.utils.view.image;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.zj.utils.R;
import com.zj.utils.utils.utilcode.ImageUtils;
import com.zj.utils.utils.utilcode.ToastUtils;

import java.util.ArrayList;
import java.util.List;




public class ReleaseMsgAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int ITEM_TYPE_ONE = 0x00001;
    private static final int ITEM_TYPE_TWO = 0x00002;
    private final LayoutInflater inflater;
    private int themeId= R.style.picture_default_style;
    private Activity context;
    private List<ImageBean> mList;


    /**
     * 这里之所以用多行视图，因为我们默认的有一张图片的（那个带+的图片，用户点击它才会才会让你去选择图片）
     * 集合url为空的时候，默认显示它，当它达到集合9时，这个图片会自动隐藏。
     */
    public ReleaseMsgAdapter(Activity context, List<ImageBean> mList) {
        this.context = context;
        this.mList = mList;
        inflater = LayoutInflater.from(context);
        onDeleteItemListener= (OnDeleteItemListener) context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        parent.setPadding(20, 0, 20, 0);
        switch (viewType) {
            case ITEM_TYPE_ONE:
                return new MyHolder(inflater.inflate(R.layout.activity_message_item, parent, false));
            case ITEM_TYPE_TWO:
                return new MyTWOHolder(inflater.inflate(R.layout.activity_message_two_items, parent, false));
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyHolder) {
            bindItemMyHolder((MyHolder) holder, position);
        } else if (holder instanceof MyTWOHolder) {
            bindItemTWOMyHolder((MyTWOHolder) holder, position);
        }
    }

    private void bindItemTWOMyHolder(final MyTWOHolder holder, int position) {
      /*  if (listSize() >=4) {//集合长度大于等于9张时，隐藏 图片
            holder.imageview2.setVisibility(View.GONE);
        } else {
            holder.imageview2.setVisibility(View.VISIBLE);
        }*/
        holder.imageview2.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(View v) {
                if (listSize()>=5) {
                    ToastUtils.showLong("图片最多五个");
                }else{
                    PictureSelector.create(context)
                            .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                            .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                            .maxSelectNum(5-listSize())//TODO 王飞 最大图片选择数量需要减去已近又得哦。
                            .minSelectNum(1)// 最小选择数量
                            .imageSpanCount(4)// 每行显示个数
                            .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE  多选 PictureConfig.SINGLE)//  单选
                            .previewImage(true)// 是否可预览图片
                            .previewVideo(true)// 是否可预览视频
                            .enablePreviewAudio(true) // 是否可播放音频
                            .isCamera(true)// 是否显示拍照按钮
                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                            .enableCrop(false)// 是否裁剪
                            .compress(true)// 是否压缩
                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                            .glideOverride(100, 100)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                            .openClickSound(false)// 是否开启点击声音
                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

                }
            }
        });
    }

    private void bindItemMyHolder(final MyHolder holder, final int position) {
       /* Glide.with(context)
                .load(mList.get(position).getPath())
                .into(holder.imageview);*/
        Bitmap bmpDefaultPic = BitmapFactory.decodeFile(mList.get(position).getPath());
        Log.e("傻星星", "bindItemMyHolder: "+ mList.get(position).getPath());
        holder.imageview.setImageBitmap(ImageUtils.scale(bmpDefaultPic, 120, 120));
        holder.imageview.setOnClickListener(v -> {
            ArrayList<String> paths = new ArrayList<>();
            for (int i = 0; i < mList.size(); i++) {
                paths.add(mList.get(i).getPath());
            }
            PopupReviewImage.getInstance().show(context, holder.imageview, paths, position );
            //arrayList = PopupReviewImage.getInstance().showDelete(true);
        });
        holder.itemsLlDelete.setOnClickListener(view -> {
            int index = holder.getAdapterPosition();
            // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
            // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
            if (index != RecyclerView.NO_POSITION) {
                /*mList.remove(index);
                notifyItemRemoved(index);
                notifyItemRangeChanged(index, mList.size());*/
                if (onDeleteItemListener != null) {
                    onDeleteItemListener.OnDeleteItem(index);
                }
            }
        });
    }

    private OnDeleteItemListener onDeleteItemListener;

    public interface OnDeleteItemListener {
        void OnDeleteItem(int position);
    }

    public void setOnDeleteItemListener(OnDeleteItemListener onDeleteItemListener) {
        if (this.onDeleteItemListener==null) {
            this.onDeleteItemListener = onDeleteItemListener;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            return ITEM_TYPE_TWO;
        } else {
            return ITEM_TYPE_ONE;
        }
    }

    @Override
    public int getItemCount() {
        return mList.size() + 1;
    }

    //对外暴露方法  。点击添加图片（类似于上啦加载数据）

    public void addMoreItem(ArrayList<String> loadMoreData) {
        //mList.addAll(loadMoreData);
        notifyDataSetChanged();
    }
    //得到集合长度

    private int listSize() {
        return mList.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {
        private final ImageView imageview;
        private final LinearLayout itemsLlDelete;

        MyHolder(View itemView) {
            super(itemView);
            imageview = itemView.findViewById(R.id.imageview);
            itemsLlDelete = itemView.findViewById(R.id.itemsLlDelete);
        }

    }


    class MyTWOHolder extends RecyclerView.ViewHolder {

        private final ImageView imageview2;

        MyTWOHolder(View itemView) {
            super(itemView);
            imageview2 = itemView.findViewById(R.id.imageview2);
        }
    }
}
